package xyc.szk.eljstl.servlet;

import org.apache.commons.beanutils.BeanUtils;
import xyc.szk.eljstl.pojo.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@WebServlet("/list")
public class Test03Servlet  extends HttpServlet {
    static List<Users>  list= new ArrayList<Users>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取添加页面的用户信息 map---javaBean beanUtils
        //获取添加 页面上的所有用户信息到一个map中
        Map<String, String[]> map = req.getParameterMap();
        Users model = new Users();
        try {
            BeanUtils.populate(model,map);//将添加 页面上的数据封装到javaBean model中
            list.add(model);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //模拟一个数据库中的用户列表list
        //模拟去读数据中用户
        /*for (int i=0;i<10;i++){
            //动态生成一个user
            Users user = new Users(i+1000, "tom" + Integer.toString(i + 1), "123", i + 20);
            list.add(user);//将用户加入 到集合list中
        }*/
        req.setAttribute("users",list);//将用户列表存入到请求域 中，并将该 请求转发到页面list.jsp
        req.getRequestDispatcher("/list.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
